package com.lx.fav.util;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.po.LikeTable;
import com.lx.fav.dao.UserMapper;
import com.lx.fav.entity.User;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.logging.log4j.Log4jImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.IOException;

public class MBHelp {

    private static SqlSessionFactory sqlSessionFactory;

    public static void configMyBatisPlus() throws IOException {

        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        MybatisConfiguration configuration = new MybatisConfiguration();
        // 驼峰命名
        configuration.setMapUnderscoreToCamelCase(true);
        // 开启返回主键值功能
        configuration.setUseGeneratedKeys(true);
        // 创建 MyBatisPlus 插件对象
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 构建 MyBatisPlus 分页插件
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(true);
        paginationInnerInterceptor.setMaxLimit(500L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        // 添加 MyBatisPlus 拦截器插件
        configuration.addInterceptor(interceptor);
        // 扫描 mapper 接口所在包
        configuration.addMappers("com.lx.fav.dao");
        // 配置日志实现
        configuration.setLogImpl(Log4jImpl.class);
        // 构建 mybatis-plus 需要的 globalconfig
        GlobalConfig globalConfig = new GlobalConfig();
        // 此参数会自动生成实现 BaseMapper 的基础方法映射
        globalConfig.setSqlInjector(new DefaultSqlInjector());
        // 设置id生成器
        globalConfig.setIdentifierGenerator(new DefaultIdentifierGenerator());
        // 设置超类 mapper
        globalConfig.setSuperMapperClass(BaseMapper.class);
        // 给 configuration 注入 GlobalConfig 里面的配置
        GlobalConfigUtils.setGlobalConfig(configuration, globalConfig);
        // 设置数据源
        Environment environment = new Environment("数据库环境名",
                new JdbcTransactionFactory(),
                new PooledDataSource("com.mysql.jdbc.Driver",
                        "jdbc:mysql://127.0.0.1:3306/fav",
                        "root",
                        "aaaa"));
        configuration.setEnvironment(environment);
        // 构建 sqlSessionFactory
        sqlSessionFactory = builder.build(configuration);
//        this.session = sqlSessionFactory.openSession();
    }

    public static <O> O execute(java.util.function.Function<SqlSession, O> fun){
        SqlSession session = MBHelp.getSession();
        try{
            /*UserMapper mapper = session.getMapper(UserMapper.class);
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getName, "张三"); //XXX = #{xxx}
//            lqw.like(User::getPhone, "12"); //自动补全百分号
            mapper.selectList(lqw).forEach(System.out::println);*/
            O ref = fun.apply(session);
            session.commit();
            return ref;
        }catch (Exception e){
            session.rollback();
            throw new RuntimeException("执行sql语句失败", e);
        }finally {
            session.close();
        }
    }

    public static void generate(){
        // 使用 FastAutoGenerator 快速配置代码生成器
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/fav", "root", "aaaa")
                .globalConfig(builder -> {
                    builder.author("lx") // 设置作者
                            .outputDir("src/main/java"); // 输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.lx.fav") // 设置父包名
                            .entity("entity") // 设置实体类包名
                            .mapper("dao") // 设置 Mapper 接口包名
                            .service("service") // 设置 Service 接口包名
                            .serviceImpl("service.impl") // 设置 Service 实现类包名
                            .xml("mappers"); // 设置 Mapper XML 文件包名
                })
                .strategyConfig(builder -> {
                    builder.likeTable(new LikeTable("%"))
//                            .addInclude("table1", "table2") // 设置需要生成的表名
                            .entityBuilder()
                            .enableLombok() // 启用 Lombok
                            .enableTableFieldAnnotation() // 启用字段注解
                            .controllerBuilder()
                            .enableRestStyle(); // 启用 REST 风格
                })
//                .templateEngine(new FreemarkerTemplateEngine()) // 使用 Freemarker 模板引擎
                .execute(); // 执行生成
    }

    static {
        try {
            configMyBatisPlus();
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }

    public static void main(String[] args) {

        generate();
    }
}
